package com.xxx.control.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import java.util.Random;


/**
 * desc: MvpFragment 基类,支持懒加载
 * androidx 实现懒加载的方法：每次重新进入后会执行onResume()
 * 1.使用FragmentPagerAdapter时：
 * 使用 FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) 构造函数；
 * FragmentStatePagerAdapter 同理。当Viewpager中fragment数量多的时候用FragmentStatePagerAdapter，反之则用FragmentPagerAdapter
 * 2.使用add+show+hide模式加载fragment：
 * 默认显示位置[showPosition]的Fragment，最大 Lifecycle(setMaxLifecycle)为Lifecycle.State.RESUMED；
 * 其他隐藏的Fragment，最大Lifecycle为Lifecycle.State.STARTED。
 * 参考： https://github.com/AndyJennifer/AndroidxLazyLoad
 */
public abstract class BaseLazyFragment extends Fragment {

    /**
     * Activity对象
     */
    protected AppCompatActivity mActivity;

    protected View mRootView;
    /**
     * 是否进行过懒加载
     */
    private boolean isLazyLoad;

    /**
     * 是否进行了懒加载
     */
    protected boolean isLazyLoad() {
        return isLazyLoad;
    }

    /**
     * 当前 Fragment 是否可见
     */

    /**
     * 获得全局的 Activity
     */
    @SuppressWarnings("unchecked")
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = (AppCompatActivity) requireActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null && getLayoutId() > 0) {
            mRootView = inflater.inflate(getLayoutId(), null);
        }

        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }

        return mRootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isLazyLoad && !isHidden()) {
            initLazyLoad();
            isLazyLoad = true;
        } else {
            onRestart();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isLazyLoad = false;
    }


    protected void onRestart() {
        initData();
    }

    /**
     * 初始化懒加载
     */
    protected void initLazyLoad() {
        if (!isLazyLoad) {
            isLazyLoad = true;
            initView();
            initData();
        }
    }

    @Override
    public View getView() {
        return mRootView;
    }


    /**
     * 引入布局
     */
    protected abstract int getLayoutId();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 根据资源 id 获取一个 View 对象
     */
    protected <V extends View> V findViewById(@IdRes int id) {
        return mRootView.findViewById(id);
    }

    protected <V extends View> V findActivityViewById(@IdRes int id) {
        return mActivity.findViewById(id);
    }

    /**
     * startActivity 方法优化
     */

    public void startActivity(Class<? extends Activity> cls) {
        startActivity(new Intent(mActivity, cls));
    }

    public void startActivityFinish(Class<? extends Activity> cls) {
        startActivityFinish(new Intent(mActivity, cls));
    }

    public void startActivityFinish(Intent intent) {
        startActivity(intent);
        finish();
    }

    /**
     * startActivityForResult 方法优化
     */

    private BaseActivity.OnActivityCallback mActivityCallback;
    private int mActivityRequestCode;

    public void startActivityForResult(Class<? extends Activity> cls, BaseActivity.OnActivityCallback callback) {
        startActivityForResult(new Intent(mActivity, cls), null, callback);
    }

    public void startActivityForResult(Intent intent, BaseActivity.OnActivityCallback callback) {
        startActivityForResult(intent, null, callback);
    }

    public void startActivityForResult(Intent intent, Bundle options, BaseActivity.OnActivityCallback callback) {
        // 回调还没有结束，所以不能再次调用此方法，这个方法只适合一对一回调，其他需求请使用原生的方法实现
        if (mActivityCallback == null) {
            mActivityCallback = callback;
            // 随机生成请求码，这个请求码在 0 - 255 之间
            mActivityRequestCode = new Random().nextInt(255);
            startActivityForResult(intent, mActivityRequestCode, options);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (mActivityCallback != null && mActivityRequestCode == requestCode) {
            mActivityCallback.onActivityResult(resultCode, data);
            mActivityCallback = null;
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 销毁当前 Fragment 所在的 Activity
     */
    public void finish() {
        mActivity.finish();
        mActivity = null;
    }

    /**
     * 获取系统服务
     */
    public <T> T getSystemService(@NonNull Class<T> serviceClass) {
        return ContextCompat.getSystemService(mActivity, serviceClass);
    }

    /**
     * Fragment 返回键被按下时回调
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 默认不拦截按键事件，回传给 Activity
        return false;
    }

    /**
     * toast方法简化
     *
     * @param stringId
     */
    protected void toast(@StringRes int stringId) {
        toast(getString(stringId));
    }

    protected void toast(CharSequence content) {
        Toast.makeText(getContext(), content, Toast.LENGTH_SHORT).show();
    }

    protected void toastLong(@StringRes int stringId) {
        toast(getString(stringId));
    }

    protected void toastLong(CharSequence content) {
        Toast.makeText(getContext(), content, Toast.LENGTH_LONG).show();
    }


}